<?php
namespace app\home\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
require_once (APP_PATH . 'api/RewardApi.php');
require_once (APP_PATH . 'api/FinanceApi.php');
class Baodan extends Base{
	//空操作
	public function _initialize(){
		parent::_initialize();
		
	}
	/**
	 * 会员激活
	 */
	public function kaitong(){
		
		$finance = new \FinanceApi();
		$reward = new \RewardApi();
		$session = session::get();
		//被激活用户信息	
		$jihuo_id=I('member_id');//要激活的用户id
		$jihuo = DB::name('App_member_relation')->where(array('member_id'=>$jihuo_id))->find();//要激活的用户信息
		$user = Db::name('Users')->where(array('userId'=>$jihuo_id))->find();
		
		$member = DB::name('App_member_relation')->where(array('member_id'=>$session['USER_KEY_ID']))->find();	//谁激活的用户信息	
		if(empty($jihuo)){
			$data['status'] = -1;
			$data['info'] = '用户不存在';
			return json($data);
		}
		if($jihuo['status']!=0){
			$data['status'] = -2;
			$data['info'] = '会员已激活';
			return json($data);
		}
		//判断激活人的用户等级
		$class = $this->getUserMoneyByLevel($jihuo['level']);
		//查看激活使用哪个积分
		$account = DB::name('App_account_type')->where(array('jihuo'=>1))->find();
		
		//用户积分余额
		$member_account = DB::name('App_member_account')->where(array('member_id'=>$session['USER_KEY_ID']))->find();
		if($member_account['account_type_'.$account['id']]<$class['money']){
			$data['status'] = -3;
			$data['info'] = '您的'.$account['name'].'不足';
			return json($data);
		}
		//扣钱
		$r[] = DB::name('App_member_account')->where(array('member_id'=>$session['USER_KEY_ID']))->setDec('account_type_'.$account['id'],$class['money']);
		
		//添加日志
		$r[] = $finance->addFinance($session['USER_KEY_ID'], 1,'帮助'.$user['loginName'].'开通'.$class['level'].'会员，扣除'.$account['name'].$class['money'],2,$class['money'],$account['id']);
		
		//奖励流程
		$r[] = $reward->begin($jihuo_id, $class['money']);
		//激活后续操作
		$r[] = $this->afterJiHuo($jihuo);
		if($r){
			$data['status'] = 1;
			$data['info'] = '开通成功';
			return json($data);
		}else{
			$data['status'] = -3;
			$data['info'] = '开通失败';
			return json($data);
		}
		
	}
	/**
	 * 激活后续操作
	 * 为推荐人加推荐人数
	 * 修改被激活人的状态
	 * @param unknown $member_id
	 */
	public function afterJiHuo($member){
		$map['member_id'] = $member['zhuceid'];
		//为推荐人添加推家人数
		$res[] = Db::name('App_member_relation')->where($map)->setInc('zhitui_num',1);
		//修改会员状态
		$where['member_id'] = $member['member_id'];
		$data['status'] = 1;
		$res[] = Db::name('App_member_relation')->where($where)->update($data);
		return $res;
	}
	
	
	public function jihuo_del(){
		$uid= $_GET['uid'];
		$user=M('User')->where("uid='$uid'")->find();
		if($user['session_id']!=$_SESSION['userid']){
			$this->error("您不是当前记录的的操作人，没有权限删除");
		}
		$re=M('User')->where("uid='$uid'")->delete();
		if($re){
			$this->success("删除成功");
		}else {
			$this->error("删除失败");
		}
	}
	/**
	 * 会员激活
	 */
	public function shengji(){
		$finance = new \FinanceApi();
		$reward = new \RewardApi();
		$session = session::get();
		//被激活用户信息
		$member_id = input('member_id');//要激活的用户id
		$level = input('level');
		$member = DB::name('App_member_relation')->where(array('member_id'=>$member_id))->find();//要激活的用户信息
		$user = Db::name('Users')->where(array('userId'=>$member_id))->find();
	
		if(empty($member)){
			$data['status'] = -1;
			$data['info'] = '用户不存在';
			return json($data);
		}
		$old_level = $member['level'];
		//判断激活人的用户等级
		$class_old = $this->getUserMoneyByLevel($old_level);
		$class_new = $this->getUserMoneyByLevel($level);
		$chajia = $class_new['money'] -  $class_old['money'];
		
		//查看激活使用哪个积分
		$account = DB::name('App_account_type')->where(array('jihuo'=>1))->find();
	
		//用户积分余额
		$member_account = DB::name('App_member_account')->where(array('member_id'=>$session['USER_KEY_ID']))->find();
		if($member_account['account_type_'.$account['id']] < $class_new['money']){
			$data['status'] = -3;
			$data['info'] = '您的'.$account['name'].'不足';
			return json($data);
		}
		//扣钱
		$r[] = DB::name('App_member_account')->where(array('member_id'=>$session['USER_KEY_ID']))->setDec('account_type_'.$account['id'],$class_new['money']);
		
		//添加日志
		$r[] = $finance->addFinance($session['USER_KEY_ID'], 15,'帮助'.$user['loginName'].'升级'.$class_new['name'].'会员，扣除'.$account['name'].$class_new['money'],2,$class_new['money'],$account['id']);
		$level_data['level'] = $level;
		$r[] = Db::name('App_member_relation')->where(array('member_id'=>$session['USER_KEY_ID']))->update($level_data);
		//奖励流程
		$r[] = $reward->begin($member_id, $chajia);
		if($r){
			$data['status'] = 1;
			$data['info'] = '开通成功';
			return json($data);
		}else{
			$data['status'] = -3;
			$data['info'] = '开通失败';
			return json($data);
		}
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 订单
	 * @param unknown $member_id
	 * @param unknown $type
	 * @return string
	 */
	public function addOrder($member_id,$type){
		$member = M('Member')->where(array('member_id'=>$member_id))->find();
		$where['member_id'] = $member_id;
		$where['status'] = 1;
		$address = M('Address')->where($where)->find();
		//获得地址信息
		$arr = $this->getAddressName($address);
		//订单金额
		$goods = $this->getGoodsArr($member['level'],$type);
		foreach($goods as $m=>$n){
			$data['member_id'] = $member_id;
			$data['goods_id'] = $goods[$m]['id'];
			$data['num'] = $goods[$m]['gnum'];
			$data['price'] = $goods[$m]['bprice'];
			$data['all_money'] = $goods[$m]['all_money'];
			$data['add_time'] = time();
			$data['status'] = 0;
			$r[] = M('Orders')->add($data);
		}
		return $r;
	}
	
	public function send_post1($url, $post_data) {
	
		$postdata = http_build_query($post_data);
		$options = array(
				'http' => array(
						'method' => 'POST',
						'header' => 'Content-type:text/xml',
						'content' => $post_data,
						'timeout' => 15 * 60 // 超时时间（单位:s）
				)
		);
		$context = stream_context_create($options);
		$result = file_get_contents($url, false, $context);
	
		return $result;
	}
	/**
	 * 随机生成订单号
	 * @return number
	 */
	public function judgeVdef(){
		//随机生成5位数
		$number = rand(10000,99999);
		$today = date('Ymd');
		$vdef3 = 'SQW'.$today.$number;
		$orders = M('Orders')->where(array('vdef3'=>$vdef3))->select();
		if($orders){
			$this->judgeVdef();
		}else{
			return $vdef3;
		}	
	}
	
	
	
	/**
	 * 获得地址信息
	 * @param unknown $address
	 * @return unknown
	 */
	public function getAddressName($address){
		$aa = M('Areas')->where(array('area_id'=>$address['province_id']))->find();
		$bb = M('Areas')->where(array('area_id'=>$address['city_id']))->find();
		$cc = M('Areas')->where(array('area_id'=>$address['area_id']))->find();
		
		$arr['province'] = $aa['area_name'];
		$arr['city'] = $bb['area_name'];
		$arr['area'] = $cc['area_name'];
		return $arr;
	}
	

	/**
	 * 获得商品数组
	 * @param unknown $id
	 * @param unknown $type
	 * @return Ambigous <\Think\mixed, boolean, string, NULL, mixed, unknown, multitype:, object>
	 */
	public function getGoodsArr($id,$type){
		if($id == 1){
			if($type == 1){
				$aa[] = 29;
				$aa[] = 28;
				$where['id'] = array('in',$aa);
			}
			if($type == 2){
				$where['id'] = 30;
			}
			$goods = M('Goods')->where($where)->select();
			foreach($goods as $m=>$n){
				$goods[$m]['gnum'] = 1;
				$goods[$m]['all_money'] = $goods[$m]['bprice']*1;
			}
		}else{
			$level = M('Level')->where(array('id'=>$id))->find();
			
			if(!empty($level['goods_id'])){
				$arr_gid = explode(',', $level['goods_id']);//获取该等级的商品
			}
			if(!empty($level['goodsnum'])){
				$arr_gnum = explode(',', $level['goodsnum']);//获取该等级的商品的数量
			}
			for($i=0;$i<count($arr_gid);$i++){//遍历出对应的币种 和开通后获得的奖励
				$arr[$arr_gid[$i]]['id'] = $arr_gid[$i];
				$arr[$arr_gid[$i]]['gnum'] =$arr_gnum[$i];
			}
			$goods = M('Goods')->select();//获取所有的商品
			foreach($goods as $k=>$v){
				if(in_array($goods[$k]['id'],$arr_gid)){
					$goods[$k]['status'] = 1;//让当前拥有的币种变成默认的
					$goods[$k]['gnum'] = $arr[$goods[$k]['id']]['gnum'];//显示对应的钱数
					$goods[$k]['all_money'] = $goods[$k]['gnum']*$goods[$k]['bprice'];
				}else{
					unset($goods[$k]);//如果不存在就不默认
				}
			}
		}
// 		dump($goods);
		return $goods;
		
	}
	
	
	

}